package com.bocai.grainshop.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.bocai.common.utils.R;
import com.bocai.grainshop.product.entity.*;
import com.bocai.grainshop.product.feign.SeckillFeignService;
import com.bocai.grainshop.product.service.*;
import com.bocai.grainshop.product.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bocai.common.utils.PageUtils;
import com.bocai.common.utils.Query;

import com.bocai.grainshop.product.dao.SkuInfoDao;
import org.springframework.util.StringUtils;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {


    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SeckillFeignService seckillFeignService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.save(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wrapper = new QueryWrapper<>();

        String key = (String) params.get("key");

        if(StringUtils.hasText(key)){
            wrapper.and(obj->{
                obj.eq("sku_id",key).or().like("sku_name",key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if(StringUtils.hasText(catelogId) && !"0".equals(catelogId)){
            wrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String) params.get("brandId");
        if(StringUtils.hasText(brandId) && !"0".equals(brandId)){
            wrapper.eq("brand_id",brandId);
        }

        String min = (String) params.get("min");
        if(StringUtils.hasText(min) && !"0".equals(min)){
            wrapper.ge("price",min);
        }

        String max = (String) params.get("max");
        if(StringUtils.hasText(max) && !"0".equals(max)){
            try {
                BigDecimal bigDecimal = new BigDecimal(max);
                if(bigDecimal.compareTo(new BigDecimal("0")) == 1){

                    wrapper.le("price",max);
                }
            }catch (Exception e){

            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSpusBySpuId(Long spuId) {
        List<SkuInfoEntity> spu_id = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));

        return spu_id;
    }

    @Override
    public ItemVo getMessageBySkuId(Long skuId) {
        ItemVo itemVo = new ItemVo();

        CompletableFuture<SkuInfoEntity> supplyAsync = CompletableFuture.supplyAsync(() -> {
            //获取sku的基本信息
            SkuInfoEntity byId = this.getById(skuId);

            itemVo.setInfo(byId);
            return byId;
        }, executor);

        //上一个线程完成后 执行
        CompletableFuture<Void> attrSaleFuture = supplyAsync.thenAcceptAsync((res) -> {
            //获取spu的销售属性
            List<SkuItemSaleAttrVo> saVo = skuSaleAttrValueService.getAllSaleAttrByspuId(res.getSpuId());

            itemVo.setSaleAttr(saVo);

        }, executor);

        //与上一个then同步
        CompletableFuture<Void> spuFuture = supplyAsync.thenAcceptAsync((res) -> {
            //spu的介绍
            Long spuId = res.getSpuId();

            SpuInfoDescEntity id = spuInfoDescService.getById(spuId);

            itemVo.setDesp(id);
        }, executor);

        CompletableFuture<Void> spuAttrFuture = supplyAsync.thenAcceptAsync((res) -> {
            //spu的规格参数
            List<SpuItemAttrGroupVo> attrGroup = attrGroupService.getAttrGroupwithAttrBySpuId(res.getSpuId(), res.getCatalogId());

            itemVo.setGroupAttrs(attrGroup);
        }, executor);

        CompletableFuture<Void> imgFuture = CompletableFuture.runAsync(() -> {
            //获取sku的图片信息
            List<SkuImagesEntity> sku_id = skuImagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId));

            itemVo.setImages(sku_id);

        }, executor);

        //远程查询商品的秒杀信息
        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            //3、远程调用查询当前sku是否参与秒杀优惠活动
            R skuSeckilInfo = seckillFeignService.getSeckillMsgBySkuId(skuId);
            Object code = skuSeckilInfo.get("code");
            String s = JSON.toJSONString(code);
            Integer codeNum = JSON.parseObject(s, new TypeReference<Integer>() {
            });
            if (codeNum == 0) {
                //查询成功
                Object to = skuSeckilInfo.get("to");
                String vo = JSON.toJSONString(to);
                SeckillSkuVo seckillSkuVo = JSON.parseObject(vo, new TypeReference<SeckillSkuVo>() {
                });

                itemVo.setSeckillSkuVo(seckillSkuVo);

                if (seckillSkuVo != null) {
                    long currentTime = System.currentTimeMillis();
                    if (currentTime > seckillSkuVo.getEndTime()) {
                        itemVo.setSeckillSkuVo(null);
                    }
                }
            }
        }, executor);

        try {
            //等待所有线程完成  阻塞模式
            CompletableFuture.allOf(attrSaleFuture,spuAttrFuture,spuFuture,imgFuture,seckillFuture).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return itemVo;
    }

}